package com.padakeji.android.tumou.util;

import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.BaseJsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.ResponseHandlerInterface;
import com.padakeji.android.tumou.TuMouApplication;
import com.padakeji.android.tumou.sys.Settings;
import org.apache.http.Header;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntityHC4;
import java.util.Locale;

/**
 * Created by AtanL on 2015/9/10.
 */
public class AsyncHttpClientWrapper {

    private static AsyncHttpClientWrapper instance;

    private AsyncHttpClient mClient;

    private AsyncHttpClientWrapper() {
        mClient = new AsyncHttpClient();
    }

    public synchronized static AsyncHttpClientWrapper getInstance() {
        if (instance == null) {
            instance = new AsyncHttpClientWrapper();
        }
        return instance;
    }

    public void get(int serviceId, RequestParams params, BaseJsonHttpResponseHandler responseHandler, Object... pathVariable) {
        String url = getAbsoluteUrl(serviceId, pathVariable);
        mClient.get(url, params, responseHandler);
    }

    public void post(int serviceId, Header[] headers, JSONObject postJson, BaseJsonHttpResponseHandler responseHandler, Object... pathVariable) {
        String url = getAbsoluteUrl(serviceId, pathVariable);
        ContentType contentType = ContentType.create("application/json", "utf-8");
        StringEntityHC4 entity = new StringEntityHC4(postJson.toString(), contentType);
        mClient.post(TuMouApplication.getInstance(), url, headers, entity, "utf-8", responseHandler);
    }


    private String getAbsoluteUrl(int serviceId, Object... pathVariable) {
        String serviceFormat = TuMouApplication.getInstance().getResources().getString(serviceId);
        String service = String.format(Locale.CHINA, serviceFormat, pathVariable);
        String url = Settings.NETWORK_ACCESS_PROTOCOL + "://" + Settings.NETWORK_SERVER_HOST + Settings.NETWORK_CONTEXT_PATH + Settings.NETWORK_SERVICE_ENTRY + service;
        return url;
    }

}
